﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using BLL.CarriersBLL;
using Model;

namespace MDMUI.Carrier
{
    public partial class AddCarriers : Form
    {
        private readonly AddCarrierBll _AddCarrierbll = new AddCarrierBll();
        private int? selectedDurableSpecId = null; // 用于存储选中的耐用品规格ID
        private DataTable originalCarrierTable; // 存储原始的载具数据
        private DataTable splitCarrierTable; // 存储拆分后的载具数据

        public AddCarriers()
        {
            InitializeComponent();
            InitializeComboBoxes();

            // 绑定选择改变事件
            DurableDataGridView.SelectionChanged += DurableDataGridView_SelectionChanged;

            // 绑定载具清单表的选择改变事件
            CarrierDataGridView.SelectionChanged += CarrierDataGridView_SelectionChanged;
        }

        private void InitializeComboBoxes()
        {
            dsCB.Items.Add("All");
            dsCB.SelectedIndex = 0;
        }

        private void selectBtn_Click_1(object sender, EventArgs e)
        {
            try
            {
                // 查询耐用品表并显示在 DurableDataGridView
                List<DurableSpec> durableSpecs = _AddCarrierbll.GetAllDurableSpecs();
                DataTable durableDataTable = new DataTable();
                durableDataTable.Columns.Add("DurableSpecId", typeof(int));
                durableDataTable.Columns.Add("SpecificationDescription");
                durableDataTable.Columns.Add("Type");
                durableDataTable.Columns.Add("DetailedType");
                durableDataTable.Columns.Add("Color");
                durableDataTable.Columns.Add("MaxUsageCount");
                durableDataTable.Columns.Add("MaxUsageDays");
                durableDataTable.Columns.Add("MaxUsageCountAfterCleaning");
                durableDataTable.Columns.Add("MaxUsageDaysAfterCleaning");
                durableDataTable.Columns.Add("MaxCleaningCount");

                foreach (var spec in durableSpecs)
                {
                    DataRow row = durableDataTable.NewRow();
                    row["DurableSpecId"] = spec.DurableSpecId;
                    row["SpecificationDescription"] = spec.SpecificationDescription;
                    row["Type"] = spec.Type;
                    row["DetailedType"] = spec.DetailedType;
                    row["Color"] = spec.Color;
                    row["MaxUsageCount"] = spec.MaxUsageCount;
                    row["MaxUsageDays"] = spec.MaxUsageDays;
                    row["MaxUsageCountAfterCleaning"] = spec.MaxUsageCountAfterCleaning;
                    row["MaxUsageDaysAfterCleaning"] = spec.MaxUsageDaysAfterCleaning;
                    row["MaxCleaningCount"] = spec.MaxCleaningCount;
                    durableDataTable.Rows.Add(row);
                }

                DurableDataGridView.DataSource = durableDataTable;
                DurableDataGridView.Columns["DurableSpecId"].HeaderText = "耐用品规格号";
                DurableDataGridView.Columns["SpecificationDescription"].HeaderText = "规格说明";
                DurableDataGridView.Columns["Type"].HeaderText = "类型";
                DurableDataGridView.Columns["DetailedType"].HeaderText = "详细类型";
                DurableDataGridView.Columns["Color"].HeaderText = "颜色";
                DurableDataGridView.Columns["MaxUsageCount"].HeaderText = "最大使用次数";
                DurableDataGridView.Columns["MaxUsageDays"].HeaderText = "最大使用天数";
                DurableDataGridView.Columns["MaxUsageCountAfterCleaning"].HeaderText = "清洗后最大使用次数";
                DurableDataGridView.Columns["MaxUsageDaysAfterCleaning"].HeaderText = "清洗后最大使用天数";
                DurableDataGridView.Columns["MaxCleaningCount"].HeaderText = "最大清洗次数";

                // 清空 CarrierDataGridView
                CarrierDataGridView.DataSource = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DurableDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                // 确保只选择了一行
                if (DurableDataGridView.SelectedRows.Count != 1)
                    return;

                var selectedRow = DurableDataGridView.SelectedRows[0];
                if (selectedRow.Cells["DurableSpecId"].Value == null)
                    return;

                // 获取耐用品规格ID和类型
                int durableSpecId = (int)selectedRow.Cells["DurableSpecId"].Value;
                string maxUsageCount = selectedRow.Cells["maxUsageCount"].Value?.ToString() ?? "";
                string maxUsageDays = selectedRow.Cells["MaxUsageDays"].Value?.ToString() ?? "";

                // 更新文本框
                dsTB.Text = durableSpecId.ToString();
                dsTBS.Text = durableSpecId.ToString();
                muTB.Text = maxUsageCount.ToString();
                mcTB.Text = maxUsageDays.ToString();


                selectedDurableSpecId = durableSpecId;

                // 查询并显示关联的载具数据
                var carrierMsg = _AddCarrierbll.SearchCarrierListsByDurableSpecId(durableSpecId);

                DataTable carrierDataTable = new DataTable();
                var desiredColumns = new List<string> {
                    "CarrierId", "CarrierType", "DetailedCarrierType", "DurableSpecId",
                    "CarrierStatus", "CleaningStatus", "LockStatus", "CapacityStatus",
                    "BatchId", "Quantity", "LocationNumber","CarrierCapacity"
                };

                foreach (var column in desiredColumns)
                {
                    // 为CarrierCapacity列指定double类型
                    if (column == "CarrierCapacity")
                        carrierDataTable.Columns.Add(column, typeof(double));
                    else
                        carrierDataTable.Columns.Add(column);
                }

                foreach (var dict in carrierMsg)
                {
                    DataRow row = carrierDataTable.NewRow();
                    foreach (var column in desiredColumns)
                    {
                        if (dict.TryGetValue(column, out var value))
                        {
                            row[column] = value;
                        }
                        else
                        {
                            row[column] = DBNull.Value;
                        }
                    }
                    carrierDataTable.Rows.Add(row);
                }

                // 保存原始载具数据
                originalCarrierTable = carrierDataTable.Copy();

                CarrierDataGridView.DataSource = carrierDataTable;
                //CarrierDataGridView.Columns["CarrierId"].HeaderText = "载具号";
                //CarrierDataGridView.Columns["DurableSpecId"].HeaderText = "耐用品规格号";
                //CarrierDataGridView.Columns["BatchId"].HeaderText = "批次号";
                //CarrierDataGridView.Columns["CarrierType"].HeaderText = "载具类型";
                //CarrierDataGridView.Columns["DetailedCarrierType"].HeaderText = "载具详细类型";
                //CarrierDataGridView.Columns["CarrierStatus"].HeaderText = "载具状态";
                //CarrierDataGridView.Columns["CleaningStatus"].HeaderText = "清洗状态";
                //CarrierDataGridView.Columns["LockStatus"].HeaderText = "锁定状态";
                //CarrierDataGridView.Columns["CapacityStatus"].HeaderText = "容量状态";
                //CarrierDataGridView.Columns["Quantity"].HeaderText = "批次数量";
                //CarrierDataGridView.Columns["LocationNumber"].HeaderText = "位置号";
                //CarrierDataGridView.Columns["CarrierCapacity"].HeaderText = "载具容量";
                SetCarrierDataGridHeaders();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CarrierDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                // 确保只选择了一行
                if (CarrierDataGridView.SelectedRows.Count != 1)
                    return;

                var selectedRow = CarrierDataGridView.SelectedRows[0];
                UpdateCarrierTextBoxes(selectedRow);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UpdateCarrierTextBoxes(DataGridViewRow selectedRow)
        {
            // 获取载具数据
            string carrierType = selectedRow.Cells["CarrierType"].Value?.ToString() ?? "";
            string capacityStatus = selectedRow.Cells["CapacityStatus"].Value?.ToString() ?? "";
            string locationNumber = selectedRow.Cells["LocationNumber"].Value?.ToString() ?? "";
            string carrierId = selectedRow.Cells["CarrierId"].Value?.ToString() ?? "";


            // 更新载具相关的文本框
            ctTB.Text = carrierType;
            cTB.Text = capacityStatus;
            areaCB.Text = locationNumber;
            carrierIdTB.Text = carrierId;
        }

        private void SetCarrierDataGridHeaders()
        {
            if (CarrierDataGridView.Columns.Count == 0) return;

            CarrierDataGridView.Columns["CarrierId"].HeaderText = "载具号";
            CarrierDataGridView.Columns["DurableSpecId"].HeaderText = "耐用品规格号";
            CarrierDataGridView.Columns["BatchId"].HeaderText = "批次号";
            CarrierDataGridView.Columns["CarrierType"].HeaderText = "载具类型";
            CarrierDataGridView.Columns["DetailedCarrierType"].HeaderText = "载具详细类型";
            CarrierDataGridView.Columns["CarrierStatus"].HeaderText = "载具状态";
            CarrierDataGridView.Columns["CleaningStatus"].HeaderText = "清洗状态";
            CarrierDataGridView.Columns["LockStatus"].HeaderText = "锁定状态";
            CarrierDataGridView.Columns["CapacityStatus"].HeaderText = "容量状态";
            CarrierDataGridView.Columns["Quantity"].HeaderText = "批次数量";
            CarrierDataGridView.Columns["LocationNumber"].HeaderText = "位置号";
            CarrierDataGridView.Columns["CarrierCapacity"].HeaderText = "载具容量";
        }

        private void clearBtn_Click(object sender, EventArgs e)
        {
            numericUpDown.Value = 1;
        }

        private void createBtn_Click(object sender, EventArgs e)
        {
            try
            {

                // 检查是否有选中的行
                if (CarrierDataGridView.SelectedRows.Count == 0)
                {
                    MessageBox.Show("请先选择要拆分的载具行。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取选中的行
                var selectedRow = CarrierDataGridView.SelectedRows[0];

                // 检查是否有原始载具数据
                if (originalCarrierTable == null || originalCarrierTable.Rows.Count == 0)
                {
                    MessageBox.Show("没有载具数据，请先选择耐用品规格并加载载具数据。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取拆分数量
                int splitCount = (int)numericUpDown.Value;
                if (splitCount <= 1)
                {
                    MessageBox.Show("生成数量必须大于1。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 创建新的数据表来存储拆分后的数据
                DataTable splitTable = originalCarrierTable.Clone();

                // 获取选中的载具行数据
                DataRow selectedDataRow = ((DataRowView)selectedRow.DataBoundItem).Row;

                // 获取原始载具容量
                double originalCapacity = 0;
                if (selectedDataRow["CarrierCapacity"] != DBNull.Value)
                {
                    originalCapacity = Convert.ToDouble(selectedDataRow["CarrierCapacity"]);
                }

                // 计算拆分后的容量
                double splitCapacity = originalCapacity / splitCount;

                // 创建拆分后的行
                for (int i = 0; i < splitCount; i++)
                {
                    DataRow newRow = splitTable.NewRow();

                    // 复制选中的行的所有数据
                    foreach (DataColumn column in splitTable.Columns)
                    {
                        newRow[column.ColumnName] = selectedDataRow[column.ColumnName];
                    }

                    // 更新载具容量
                    newRow["CarrierCapacity"] = splitCapacity;

                    // 添加后缀到载具号（可选）
                    string carrierId = selectedDataRow["CarrierId"].ToString();
                    newRow["CarrierId"] = $"{carrierId}-{i + 1}";

                    splitTable.Rows.Add(newRow);
                }

                // 保存拆分后的数据
                splitCarrierTable = splitTable.Copy();

                // 显示拆分后的数据
                CarrierDataGridView.DataSource = splitTable;
                SetCarrierDataGridHeaders();

                MessageBox.Show($"操作成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"拆分失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void certainBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (splitCarrierTable == null || splitCarrierTable.Rows.Count == 0)
                {
                    MessageBox.Show("没有可传输的载具数据，请先拆分载具数据。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 使用 DataTransferService 传递数据
                DropCarrierBll.SetData(splitCarrierTable);

                MessageBox.Show("创建成功");
                // 创建 DropCarriers 窗体
                //DropCarriers dropForm = new DropCarriers();
                //dropForm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"传输数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}